package servlet.register;

import org.apache.commons.lang3.RandomStringUtils;
import redis.clients.jedis.Jedis;
import util.JedisUtil;
import util.SmsUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet(urlPatterns = "/SmsServlet",name = "SmsServlet")
public class SmsServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req,resp);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");

        String phone = request.getParameter("phone");

        // 模板1的形式为：【云通讯】您使用的是云通讯短信模板，您的验证码是{1}，请于{2}分钟内正确输入。
        String templateId= "1";

        //随机生成4位数字作为验证码
        String code = RandomStringUtils.randomNumeric(4);
        //过期时间,单位分钟
        String expire = "5";

        String[] datas = {code, expire};

        //发送短信
        boolean result = SmsUtil.sendSms(phone, templateId, datas);

        if (!result) {
            response.getWriter().print("0");
        }

        //将验证码存储到redis
        Jedis jedis = JedisUtil.getJedis();
        jedis.setex("register::"+phone, Integer.parseInt(expire)*60, code);
        JedisUtil.closeJedis(jedis);

        response.getWriter().print("1");


    }
}
